package com.eveinfo.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;

import com.eveinfo.api.accessors.NameToId;

public class Setting {

	public static String FILE_NAME = "EveInfoOptions.txt";

	public static void deleteCacheFiles(Context context) {
		File dir = context.getDir("cache", 0);
		if (dir != null && dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				new File(dir, children[i]).delete();
			}
			dir.delete();
		}
		context.getDir("cache", 0);
		Parsers.deleteCache();
	}
	
	public static void deletePlannersFiles(Context context) {
		File dir = context.getDir("planner", 0);
		if (dir != null && dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				new File(dir, children[i]).delete();
			}
			dir.delete();
		}
		context.getDir("planner", 0);
		Parsers.deleteCache();
	}

	public static void writeOption(Context context, List<Pilot> pilots) {
		FileOutputStream fos;
		try {
			context.deleteFile(FILE_NAME);
			fos = context.openFileOutput(FILE_NAME, Context.MODE_WORLD_WRITEABLE);
			OutputStreamWriter osw = new OutputStreamWriter(fos);
			for (Pilot p : pilots) {
				osw.write(p.getName() + "," + p.getUserId() + "," + p.getCharacterId() + "," + p.getApiKey() + "\r\n");
				osw.flush();
			}
			osw.close();
		} catch (FileNotFoundException e) {
			Logging.getInstance().e(e);
			e.printStackTrace();
		} catch (IOException e) {
			Logging.getInstance().e(e);
			e.printStackTrace();
		}
	}

	public static ArrayList<Pilot> readOptions(final Context context, String dir) throws ConfigFileException {
		try {
			File file = new File(dir + FILE_NAME);
			FileInputStream fis = new FileInputStream(file);
			return readOptions(context, fis);
		} catch (FileNotFoundException e) {
			throw new ConfigFileException("Create a configuration file in your SD card called " + Setting.FILE_NAME
					+ " with inside the characters info.");
		}
	}

	public static ArrayList<Pilot> readOptions(final Context context) throws ConfigFileException {
		FileInputStream fis = null;
		try {
			fis = context.openFileInput(FILE_NAME);
			return readOptions(context, fis);
		} catch (FileNotFoundException e) {
			throw new ConfigFileException("No pilots");
		}
	}

	private static ArrayList<Pilot> readOptions(final Context context, FileInputStream fis) throws ConfigFileException {
		ArrayList<Pilot> pilots = new ArrayList<Pilot>();
		try {
			StringBuilder sb = new StringBuilder();
			int read = fis.read();
			while (read != -1) {
				sb.append((char) read);
				read = fis.read();
			}

			String options = sb.toString();
			String[] lines = options.split("\r\n");

			for (int i = 0; i < lines.length; i++) {
				Pilot pilot = new Pilot();
				String s = lines[i];
				if (s.equals(""))
					continue;
				String[] words = s.split(",");

				if (words.length < 4)
					throw new ConfigFileException("Should be : Character Name, User ID, Character ID, Api Key");

				String name = words[0];
				int userId = 0;
				try {
					userId = Integer.parseInt(words[1]);
				} catch (NumberFormatException e) {
					throw new ConfigFileException("User ID is not a Number");
				}
				String characterIdString = words[2];
				String apiKey = words[3];

				pilot.setName(name);
				pilot.setUserId(userId);
				pilot.setApiKey(apiKey);
				if (characterIdString.equals("")) {
					try {
						int characterId = new NameToId(name).getNameToId().getCharacterID();
						pilot.setCharacterId(characterId);
					} catch (Exception e) {
						AlertDialog.Builder builder = new AlertDialog.Builder(context);
						builder.setTitle(e.toString());
						builder.setMessage(e.getMessage());
						builder.show();
						e.printStackTrace();
					}

				} else {
					pilot.setCharacterId(Integer.parseInt(characterIdString));
				}
				pilots.add(pilot);
			}
			if (pilots.size() > 0)
				Setting.writeOption(context, pilots);
			return pilots;
		} catch (IOException e) {
			Logging.getInstance().e(e);
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					Logging.getInstance().e(e);
					e.printStackTrace();
				}
			}
		}
		return null;
	}

}
